﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Lk.Common.Helper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OAuth.Dapper.Models;
using OAuth.Server.Domain;
using OAuth.Server.Models.Account;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace OAuth.Server.Controllers
{
  //  [Route("api/[controller]")]
   // [ApiController]
    public class AccountController : Controller
    {
        private readonly IAccountRepository accountRepository;
        private readonly IIdentityServerInteractionService interaction;
        private readonly ILogger<AccountController> logger;
        private readonly IClientStore clientStore;
        public AccountController(IAccountRepository accountRepository, ILogger<AccountController> logger,
                IIdentityServerInteractionService interaction, IClientStore clientStore)
        {
            this.accountRepository = accountRepository;
            this.logger = logger;
            this.interaction = interaction;
            this.clientStore = clientStore;
        }


  
        public  IActionResult Login()
        {
         

            return View();
        }
       
        //  [ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<IActionResult> Login(LoginRequest request)
        {

            var context = await interaction.GetAuthorizationContextAsync(request.ReturnUrl);
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = await accountRepository.Login(request.UserName, request.Password);
            if (user == null)
            {

                ModelState.AddModelError("", "登陆失败");
                return BadRequest(ModelState);
            }
            AuthenticationProperties props = null;
            if (AccountOptions.AllowRememberLogin && request.RememberLogin)
            {
                props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                };
            };

            var claims = new List<Claim>
                    {
                        new Claim(JwtClaimTypes.PhoneNumber,user.Mobile),
                        new Claim(JwtClaimTypes.PhoneNumberVerified,((user.EncryptionType & 2)>0).ToString()),
                        new Claim(JwtClaimTypes.Email,user.Email),
                        new Claim(JwtClaimTypes.EmailVerified,((user.EncryptionType & 2)>0).ToString())
                    };
            // issue authentication cookie with subject ID and username
            await HttpContext.SignInAsync(user.Id.ToString(), user.UserName, props, claims.ToArray());
            if (context != null)
            {
                if (await clientStore.IsPkceClientAsync(context.ClientId))
                {
                    // if the client is PKCE then we assume it's native, so this change in how to
                    // return the response is for better UX for the end user.
                    return View("Redirect", new  { RedirectUrl = request.ReturnUrl });
                }

                // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                return Redirect(request.ReturnUrl);
            }

            return Ok();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(AccountRegisterReqeuest reqeuest)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }


            var model = MapperHelper<AccountRegisterReqeuest, Account>.Map(reqeuest);
            var id = await accountRepository.Insert(model);
            if (id > 0)
            {
                return Ok();
            }
            ModelState.AddModelError("", "注册失败");
            return BadRequest(ModelState);
            //return new StatusCodeResult(400);
        }


    }
}